package com.qc.book.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qc.book.dao.UserMapper;
import com.qc.book.pojo.User;

public class userServlet extends HttpServlet {

	private static final long serialVersionUID = 7706757901936514194L;
	
	Logger logger = LoggerFactory.getLogger(userServlet.class);
	private SqlSession session;
	private UserMapper um;
	
	@Override
	public void init(){
		logger.debug("初始化数据。。。");
		try {
			SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
			session = sf.openSession();
			um = session.getMapper(UserMapper.class);
		} catch (IOException e) {	
			e.printStackTrace();
		}
	}
	
	@Override
	public void destroy(){
		logger.debug("销毁数据。。。");
		if (null != session) {
			session.commit();
			session.close();
			
		}
		
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String action = request.getParameter("action");
		if (action == null || "login".equals("action")) {
			this.userLogin(request,response);
		}else if ("exit".equals(action)) {
			this.exit(request,response);
		}
		
	}

	private void exit(HttpServletRequest request, HttpServletResponse response) throws IOException {
		request.getSession().removeAttribute("userInfo");
		response.sendRedirect("login.jsp");
	}

	private void userLogin(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("username");
		String pwd = request.getParameter("password");
		
		User user = um.findUserLogin(name, pwd);
		if (null != user) {
			//登录成功
			request.getSession().setAttribute("userInfo", user);
			response.sendRedirect("bookAction");
		}else {
			//登录失败
			request.setAttribute("msg", "账号或密码错误!!!");
			request.getRequestDispatcher("login.jsp").forward(request, response);
			
		}
		
	}

	
	

}
